package tcptunnel

import (
	log "github.com/cihub/seelog"
	"net"
	"tunnel/authentication"
	"tunnel/tunnel"
)

//
// TCPAuthClientHandler
// @Description:
//
type TCPAuthClientHandler struct {
	Client *TCPClientV3
}

//
// OnMessage
// @Description:
// @receiver TCPAuthClientHandler
// @param msg
//
func (h *TCPAuthClientHandler) OnMessage(msg string) {
	log.Info("receive message from server : ", msg)
}

//
// OnReport
// @Description:
// @receiver h
// @param payload
//
func (h *TCPAuthClientHandler) OnReport(payload []byte) {
}

//
// OnLogin
// @Description:
// @receiver h
// @param err
//
func (h *TCPAuthClientHandler) OnLogin(err error) {

}

//
// OnLogout
// @Description:
// @receiver h
// @param err
//
func (h *TCPAuthClientHandler) OnLogout(err error) {
	h.Client.SetErr(err)
	h.Client.Stop()
}

//
// OnDisconnect
// @Description:
// @receiver h
//
func (h *TCPAuthClientHandler) OnDisconnect() {
	log.Info("disconnected...")
	h.Client.SetErr(tunnel.ErrDisconnect)
	h.Client.Stop()
	h.Client.multiConn.Close()
}

//
// TCPAuthServerHandler
// @Description:
//
type TCPAuthServerHandler struct {
	Server *TCPServerV3
}

//
// OnMessage
// @Description:
// @receiver h
// @param address
// @param conn
// @param packet
//
func (h *TCPAuthServerHandler) OnMessage(address string, conn *net.TCPConn, packet *authentication.TransportPacket) {
	log.Info("[address:", address, "][uuid:", packet.UUID, "] send message to server : ", string(packet.Payload))
}

//
// OnReport
// @Description:
// @receiver h
// @param packet
// @param address
//
func (h *TCPAuthServerHandler) OnReport(packet *authentication.TransportPacket, address string) {
	log.Info("[address:", address, "][uuid:", packet.UUID, "] report data to server : ", len(packet.Payload), " bytes")
}

//
// AfterLogin
// @Description:
// @receiver h
// @param packet
// @param address
//
func (h *TCPAuthServerHandler) AfterLogin(packet *authentication.TransportPacket, address string) {
	log.Info("[address:", address, "][uuid:", packet.UUID, "] login success")
}

//
// AfterLogout
// @Description:
// @receiver h
// @param packet
// @param address
//
func (h *TCPAuthServerHandler) AfterLogout(packet *authentication.TransportPacket, address string) {
	log.Info("[address:", address, "][uuid:", packet.UUID, "] logout success")
	if mt, ok := h.Server.tunnels[address]; ok && mt != nil {
		mt.Close()
		h.Server.lock.Lock()
		delete(h.Server.tunnels, address)
		h.Server.lock.Unlock()
	}
}

//
// Disconnect
// @Description:
// @receiver h
// @param address
// @param err
//
func (h *TCPAuthServerHandler) Disconnect(address string, err error) {
	log.Info("[address:", address, "] disconnected : ", err.Error())
	if mt, ok := h.Server.tunnels[address]; ok && mt != nil {
		mt.Close()
		h.Server.lock.Lock()
		delete(h.Server.tunnels, address)
		h.Server.lock.Unlock()
	}
}
